package com.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @Author 咕唧
 * @Date 2022/7/7 22:03
 * @Version 1.0
 * 简单实现一个http服务器
 */
public class HttpServer {
    public static void main(String[] args) {

        RequestUtil.inject();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup parent = new NioEventLoopGroup();
        NioEventLoopGroup child = new NioEventLoopGroup();
        serverBootstrap.group(parent, child)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                //netty内置的编码器
                                .addLast(new HttpServerCodec())
                                .addLast(new MyHttpHandler());

                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(23456).sync();
            channelFuture.addListener(channel -> {
                if (channel.isSuccess()) {
                    System.out.println("启动成功");
                } else {
                    System.out.println("启动失败");
                }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parent.shutdownGracefully();
            child.shutdownGracefully();
        }
    }
}
